from django.shortcuts import render

# Create your views here.

import json

from tools.myredis import r
from tools.baiduapi import bdapi

from user.models import UserModel
from rest_framework.views import APIView
from rest_framework.response import Response
from personalCenter.models import RealNameAuthentication
from personalCenter.ser import RealNameAuthenticationSerializer
from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import CreateAPIView
from rest_framework import status


from mycerlery.sms.tasks import send_sms
import oss2
from django.core.files.storage import default_storage
from oss2 import Bucket
from dingxiang import settings
from mycerlery.sms.tasks import idcard
from urllib.parse import quote

# ============================================ 个人中心 =======================================

# 上传图片到OSS，并返回OSS的url
class UploadImageAPIView(APIView):
    def post(self, request):
        if request.FILES.get('file'):
            # 获取上传文件
            file = request.FILES['file']
            # 生成文件名
            destination = 'uploads/%s' % file.name
            auth = oss2.Auth(settings.OSS_ACCESS_KEY_ID, settings.OSS_ACCESS_KEY_SECRET)
            bucket = Bucket(auth, settings.OSS_ENDPOINT, settings.OSS_BUCKET_NAME)
            # 上传文件
            result = bucket.put_object(destination, file)
            print(result)
            # 获取上传文件后的地址
            signed_url = bucket.sign_url('GET', destination, 3600)
            print("获取上传文件地址请求成功.............")
            print(signed_url)
            print("uploadImage:文件上传成功")
            return Response({'message': '文件上传成功', "url": signed_url})
        else:
            return Response({'error': '没有提供文件'}, status=400)

# 提交图片地址进行审核
class SubmitImageAPIView(APIView):
    def post(self, request):
        # 转换为16进制,百度平台需要读取16进制
        url = quote(request.data.get("url"))
        # 加入队列中
        print("提交的url:", url)
        r.list_push("baidu_url_list", url)
        # 异步验证
        # idcard.delay()
        return Response({'message': '图片已提交审核', 'url': url})

# 前端轮询获取身份证验证信息
class GetInfo(APIView):
    def post(self, request):
        url = request.data.get("url")
        print("轮询url:", url) # 存在且与redis中的url一致
        print("type_url:", type(url)) # str
        # http://fuguang0.oss-cn-beijing.aliyuncs.com/uploads%2Fimage-20241129185610739.png
        message = r.get_str(url)
        print("message:", message)
        if message:
            return Response({'message': json.loads(message), "code": 200})
        else:
            return Response({'message': 'No message yet.', "code": 400})

# 向用户实名认证表中添加
class RealNameAuthenticationCreateAPIView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    queryset = RealNameAuthentication.objects.all()
    serializer_class = RealNameAuthenticationSerializer

    def create(self, request, *args, **kwargs):
        data = request.data
        user = request.data.user
        # print("获取用户ID请求成功.............")
        # print(data)
        idcard_url = data.get("url")
        # print("data_message:", data.get("message"))
        message = json.loads(data.get("message"))
        the_message = json.loads(message)
        # print("message:", the_message)
        # print("type_message:", type(the_message))
        words_result = the_message.get("words_result")
        # print("words_result:", words_result)
        idcard = the_message['words_result'][-1]['words']
        name = the_message["words_result"][2]["words"]
        # print("idcard:", idcard)
        # print("name:", name)
        new_data = {"user": 6, "idcard_url": idcard_url, "idcard": idcard, "name": name}
        # print(new_data)
        serializer = self.get_serializer(data=new_data)
        serializer.is_valid(raise_exception=True)
        # print("serializer:", serializer)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        # print("添加实名认证信息请求成功.............")
        # print(serializer.data)
        # print("headers:", headers)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
